package com.tengfei.main.index.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tengfei.common.core.domain.PageQuery;
import com.tengfei.common.core.page.TableDataInfo;
import com.tengfei.common.exception.ServiceException;
import com.tengfei.common.utils.DateUtils;
import com.tengfei.common.utils.StringUtils;
import com.tengfei.common.utils.file.MimeTypeUtils;
import com.tengfei.main.course.config.AliyunConfig;
import com.tengfei.main.course.service.impl.OssServiceImpl;
import com.tengfei.main.index.domain.Banner;
import com.tengfei.main.index.domain.bo.BannerBo;
import com.tengfei.main.index.domain.vo.BannerVo;
import com.tengfei.main.index.mapper.BannerMapper;
import com.tengfei.main.index.service.IBannerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.UUID;

/**
 * 轮播图Service业务层处理
 *
 * @author tengfei
 * @date 2022-09-03
 */
@Service
@Slf4j
public class BannerServiceImpl implements IBannerService {

    @Resource
    private BannerMapper baseMapper;
    @Resource
    private AliyunConfig aliyunConfig;
    @Resource
    private OssServiceImpl ossService;

    /**
     * 查询轮播图
     */
    @Override
    public BannerVo queryById(Long bnId) {
        return baseMapper.selectVoById(bnId);
    }

    /**
     * 查询轮播图列表
     */
    @Override
    public TableDataInfo<BannerVo> queryPageList(BannerBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<Banner> lqw = new LambdaQueryWrapper<Banner>()
                .eq(ObjectUtil.isNotNull(bo.getBnIsShow()), Banner::getBnIsShow, bo.getBnIsShow())
                .like(StringUtils.isNotBlank(bo.getBnContent()), Banner::getBnContent, bo.getBnContent())
                .orderByDesc(Banner::getBnIsShow)
                .orderByDesc(Banner::getUpdateTime);
        Page<BannerVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 修改轮播图
     */
    @Override
    public Boolean updateByBo(BannerBo bo) {
        Banner update = BeanUtil.toBean(bo, Banner.class);
        return baseMapper.updateById(update) > 0;
    }


    /**
     * 批量删除轮播图
     */
    @Override
    public Boolean deleteWithValidByIds(Long bnId) {
        return baseMapper.deleteById(bnId) > 0;
    }

    @Override
    public BannerVo uploadBannerImg(MultipartFile file) {
        if (ObjectUtil.isNull(file)) {
            throw new ServiceException("上传图片为空");
        }
        long size = file.getSize();
        if (size / 1024 / 1024 > 4) {
            throw new ServiceException("上传轮播图大于4M");
        }
        String extName = FileNameUtil.extName(file.getOriginalFilename());
        boolean extFlag = false;
        for (String etx : MimeTypeUtils.IMAGE_EXTENSION) {
            if (etx.equalsIgnoreCase(extName)) {
                extFlag = true;
                break;
            }
        }
        if (!extFlag) {
            throw new ServiceException("请上传图片文件");
        }
        // 获取图片宽高
        try {
            BufferedImage read = ImageIO.read(file.getInputStream());
            int width = read.getWidth();
            int height = read.getHeight();
            double ratio = width * 1.0 / height;
            if (ratio < 1.7 || ratio > 2.3) {
                throw new ServiceException("请上传比例为16:9~21:9左右的图片");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        String fileName = UUID.randomUUID().toString();
        String filePath = new StringBuilder(aliyunConfig.getRootPath())
                .append("/resources/")
                .append(DateUtils.datePath())
                .append("/")
                .append(fileName)
                .append(".")
                .append(extName)
                .toString();
        // 持久化到数据库
        Banner banner = new Banner();
        banner.setBnUrl(aliyunConfig.getUrlPrefix() + filePath);
        banner.setBnIsShow(0);
        baseMapper.insert(banner);
        // 上传到oss
        try {
            ossService.uploadImg(filePath, file.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        BannerVo bannerVo = BeanUtil.copyProperties(banner, BannerVo.class);
        return bannerVo;
    }
}
